<template>
  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">车场管理系统</div>
      <el-form :model="param" :rules="rules" ref="login" label-width="0px" class="ms-content">
        <el-form-item prop="username">
          <el-input v-model="param.username" placeholder="username">
            <template #prepend>
              <el-button :icon="User"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              type="password"
              placeholder="password"
              v-model="param.password"
              @keyup.enter="submitForm(login)"
          >
            <template #prepend>
              <el-button :icon="Lock"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <!--        验证码-->
        <el-form-item prop="captcha" class="captchaBox">
          <el-input
              placeholder="验证码"
              v-model="param.captcha"
              @keyup.enter="submitForm(login)"
          >
            <template #prepend>
              <el-button :icon="PriceTag"></el-button>
            </template>
          </el-input>
          <el-image :src="captchaData.img" @click="getCaptcha">
            <template #error>
              <div class="image-slot" @click="getCaptcha">
                <el-icon>
                  <icon-picture/>
                </el-icon>
              </div>
            </template>
          </el-image>
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" @click="submitForm(login)">登录</el-button>
        </div>
        <!--				<p class="login-tips">Tips : 用户名和密码随便填。</p>-->
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive} from 'vue';
import {useTagsStore} from '../store/tags';
import {usePermissStore} from '../store/permiss';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import type {FormInstance, FormRules} from 'element-plus';
import {Lock, User, PriceTag, Picture as IconPicture} from '@element-plus/icons-vue';
import {useUserStore} from "@/store/user";
import {UserApi} from "@/api";
import {Md5} from 'ts-md5';
import {useCookies} from "vue3-cookies";

const {cookies} = useCookies();

interface LoginInfo {
  username: string;
  password: string;
  captcha: string;
}

const router = useRouter();
const param = reactive<LoginInfo>({
  username: 'admin',
  password: '123123',
  captcha: '',
});

const rules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
  captcha: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {
      validator: function (rule, value, callback) {
        if (captchaData.text.toUpperCase() !== value.toUpperCase()) {
          console.log(captchaData.text.toUpperCase())
          console.log(value.toUpperCase())
          callback(new Error("验证码校验失败，请重新输入"));
        } else {
          //校验通过
          callback();
        }
      }, trigger: 'blur'
    }
  ]
};
const permiss = usePermissStore();
const user = useUserStore();
const login = ref<FormInstance>();
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  const valid = await formEl.validate((valid, fields) => !!valid);
  if (!valid) {
    return false;
  }

  loginFun();
};

const loginFun = () => {
  const md5: any = new Md5()
  md5.appendAsciiStr(param.password)
  const params = {
    username: param.username,
    pass: md5.end(),
  }
  UserApi.userLogin(params).then((res: any) => {
    console.log(res, 'res')
    if (res.data.status === 1) {
      ElMessage.success('登录成功');
      cookies.set('pktoken', res.data.data.token, '7d');
      const role = res.data?.data?.userInfo?.role;
      permiss.setUserRole(role);
      user.setUserInfo(res.data?.data?.userInfo);
      router.push('/');
    } else {
      ElMessage.error(res.data.msg);
    }
  })
};

const captchaData = reactive({
  img: '',
  text: ''
});
const getCaptcha = () => {
  UserApi.getCaptcha({}).then((res: any) => {
    if (res.data.status == 1 && res.data?.data?.data) {
      const svg = res.data.data.data;
      captchaData.text = res.data.data.text;
      captchaData.img = URL.createObjectURL(new Blob([svg], {type: "image/svg+xml;charset=utf-8"}));
    } else {
      ElMessage.error(res.data?.msg)
    }
  })
};
getCaptcha();

const tags = useTagsStore();
tags.clearTags();
</script>

<style scoped lang="less">
.captchaBox {
  .el-form-item__content {
    display: flex;

    .el-input {
      flex: 1;
      margin-right: 10px;
    }

    .el-image {
      display: flex;
      align-items: center;
      justify-content: center;
      background: #ccc;
      cursor: pointer;
      height: 32px;
      min-width: 50px;

      .image-slot {
        display: flex;
      }
    }
  }
}

.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../assets/img/login-bg.jpg);
  background-size: cover;
  background-repeat: no-repeat;
}

.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #fff;
  border-bottom: 1px solid #ddd;
}

.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}

.ms-content {
  padding: 30px 30px;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}
</style>
